package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    //添加菜品或套餐
    @Override
    public Cart cartAdd(Cart cart) {
        //1.查询是否是第一次添加
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        wrapper.eq(cart.getDishId() != null, Cart::getDishId, cart.getDishId());
        wrapper.eq(cart.getSetmealId() != null, Cart::getSetmealId, cart.getSetmealId());
        Cart oneCart = cartMapper.selectOne(wrapper);
        if (oneCart==null) {//2.如果是第一次添加
            cart.setUserId(UserHolder.get().getId());
            cart.setCreateTime(new Date());
            cart.setNumber(1);
            cartMapper.insert(cart);
            return cart;
        }else {//3.如果不是第一次
            oneCart.setNumber(oneCart.getNumber()+1);
            cartMapper.updateById(oneCart);
            return oneCart;
        }
    }
    //获取购物车数据
    @Override
    public List<Cart> cartList() {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId());
        List<Cart> cartList = cartMapper.selectList(wrapper);
        return cartList;
    }
    //减少菜品或套餐
    @Override
    public Cart cartSub(Cart cart) {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId());
        wrapper.eq(cart.getDishId()!=null,Cart::getDishId,cart.getDishId());
        wrapper.eq(cart.getSetmealId() != null, Cart::getSetmealId, cart.getSetmealId());
        Cart oneCart = cartMapper.selectOne(wrapper);
        if (oneCart.getNumber()>1) {
            oneCart.setNumber(oneCart.getNumber()-1);
            cartMapper.updateById(oneCart);
            return oneCart;
        }else {
            cartMapper.deleteById(oneCart.getId());
            oneCart.setNumber(0);
            return oneCart;
        }
    }
    //清空购物车
    @Override
    public void cartClean() {
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId());
        cartMapper.delete(wrapper);
    }
}
